package com.tn.serverredis.controller;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName : RedisController  //类名
 * @Description : redis消息发布订阅测试  //描述
 * @Author : tn  //作者
 * @Date: 2020-07-08 10:54  //时间
 */
@RestController
@RequestMapping("redis")
public class RedisController {


    @Autowired
    StringRedisTemplate template;


    @RequestMapping(value = "/syncmessage")
    public String SyncMessage(){
        for(int i = 1; i <= 5; i++){
            try{
                // 为了模拟消息，sleep一下。
                Thread.sleep(2000);
            }catch(InterruptedException ex){}
            template.convertAndSend("tn", String.format("\n tn - 我是消息{%d}号: %tT", i, new Date()));
        }

        return "消息发送成功";
    }


    @GetMapping("setMessage")
    public String setMessage(){
        Map map = new HashMap();
        map.put("name","谭宁");
        map.put("sex","2");
//        template.convertAndSend("tn", map);
        template.convertAndSend("test", JSONObject.toJSONString(map));
        return "消息发送成功";
    }

}
